# metadata_storage.py - 修复版本
import os
import json
import logging
from db_pool import get_db_connection
from config import Config

logger = logging.getLogger('metadata_storage')

class MetadataStorage:
    def __init__(self):
        self.storage_type = Config.SCRIPT_STORAGE

    def save_metadata(self, metadata):
        """保存元数据"""
        if self.storage_type == 'file':
            return self._save_to_file(metadata)
        else:
            return self._save_to_database(metadata)

    def load_metadata(self):
        """加载元数据"""
        if self.storage_type == 'file':
            return self._load_from_file()
        else:
            return self._load_from_database()

    def _save_to_file(self, metadata):
        """保存到文件"""
        metadata_path = os.path.join(Config.API_DIR, 'metadata.json')
        try:
            with open(metadata_path, 'w', encoding='utf-8') as f:
                json.dump(metadata, f, indent=2, default=str)
            return True, None
        except Exception as e:
            logger.error(f"Failed to save metadata to file: {str(e)}")
            return False, str(e)

    def _load_from_file(self):
        """从文件加载"""
        metadata_path = os.path.join(Config.API_DIR, 'metadata.json')
        if not os.path.exists(metadata_path):
            return {}, None

        try:
            with open(metadata_path, 'r', encoding='utf-8') as f:
                return json.load(f), None
        except Exception as e:
            logger.error(f"Failed to load metadata from file: {str(e)}")
            return {}, str(e)

    def _save_to_database(self, metadata):
        """保存到数据库 - 修复版本"""
        connection = None
        try:
            logger.info("Saving metadata to database")
            connection = get_db_connection()
            cursor = connection.cursor()

            # 序列化元数据
            metadata_json = json.dumps(metadata, default=str)

            # 检查是否已存在
            cursor.execute(f"SELECT id FROM {Config.METADATA_TABLE} WHERE id = 1")
            exists = cursor.fetchone()

            if exists:
                # 更新现有记录
                cursor.execute(
                    f"UPDATE {Config.METADATA_TABLE} SET metadata = %s, updated_at = NOW() WHERE id = 1",
                    (metadata_json,)
                )
            else:
                # 插入新记录
                cursor.execute(
                    f"INSERT INTO {Config.METADATA_TABLE} (id, metadata) VALUES (1, %s)",
                    (metadata_json,)
                )

            connection.commit()
            logger.info("Metadata saved successfully")
            return True, None
        except Exception as e:
            logger.error(f"Database error while saving metadata: {str(e)}")
            if connection:
                connection.rollback()
            return False, str(e)
        finally:
            if connection:
                connection.close()

    def _load_from_database(self):
        """从数据库加载 - 修复版本"""
        connection = None
        try:
            logger.info("Loading metadata from database")
            connection = get_db_connection()
            cursor = connection.cursor()

            cursor.execute(
                f"SELECT metadata FROM {Config.METADATA_TABLE} WHERE id = 1"
            )
            result = cursor.fetchone()

            if result and result['metadata']:
                metadata = json.loads(result['metadata'])
                logger.info(f"Metadata loaded successfully, {len(metadata)} APIs found")
                return metadata, None
            else:
                logger.info("No metadata found in database, returning empty dict")
                return {}, None
        except Exception as e:
            logger.error(f"Database error while loading metadata: {str(e)}")
            return {}, str(e)
        finally:
            if connection:
                connection.close()

# 创建全局存储实例
metadata_storage = MetadataStorage()